package com.example.jack.community.view.me.per_setting;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.chaychan.viewlib.PowerfulEditText;
import com.example.jack.community.R;
import com.example.jack.community.data.loginbean.Code;
import com.example.jack.community.model.me.Res_phonenumView;
import com.example.jack.community.persenter.me.Res_pho_numPresenterImp;
import com.example.jack.community.view.login.LoginActivity;
import com.example.jack.community.view.login.util.CountDownTimerUtils;
import com.google.gson.Gson;

import org.zackratos.ultimatebar.UltimateBar;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

/**
 * 更换绑定手机号界面
 */
public class Res_pho_numActivity extends AppCompatActivity implements Res_phonenumView {

    //返回
    @BindView(R.id.img_back)
    ImageView imgBack;

    //手机号码输入框
    @BindView(R.id.forgetEdiPhone)
    PowerfulEditText forgetEdiPhone;


    //验证码输入框
    @BindView(R.id.forgetEdiCode)
    EditText forgetEdiCode;

    //获取手机验证码文本
    @BindView(R.id.txt_get_code)
    TextView txtGetCode;

    //确认绑定按钮
    @BindView(R.id.login_button)
    Button loginButton;

    //短信回调变量
    private EventHandler eventHandler;

    //调试log
    private static final String TAG = "TonJie";

    private Res_pho_numPresenterImp res_pho_numPersenter = new Res_pho_numPresenterImp();

    //对话框
    private SweetAlertDialog pDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rel_res);
        ButterKnife.bind(this);
        //判断验证码是否正确的回调
        code();
        //绑定Activity
        res_pho_numPersenter.attachView(this);
        //沉浸式标题栏
        status();
    }

    //沉浸式标题栏
    protected void status() {
        UltimateBar ultimateBar = new UltimateBar(Res_pho_numActivity.this);
        ultimateBar.setColorBar(ContextCompat.getColor(Res_pho_numActivity.this, R.color.color_bottom));
    }

    @OnClick({R.id.img_back, R.id.txt_get_code, R.id.login_button})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_back://返回按钮
                finish();
                break;
            case R.id.txt_get_code://获取验证码
                //实现短信倒计时
                CountDownTimerUtils mCountDownTimerUtils = new CountDownTimerUtils(txtGetCode, 60000, 1000);
                mCountDownTimerUtils.start();
                //获取验证码
                SMSSDK.getVerificationCode("86", forgetEdiPhone.getText().toString().trim());
                break;
            case R.id.login_button:
                dialog();//弹出对话框
                Log.d(TAG, "onViewClicked: login");
                String mPhone = forgetEdiPhone.getText().toString().trim();
                String code = forgetEdiCode.getText().toString().trim();
                SMSSDK.submitVerificationCode("86", mPhone, code);
                break;
        }
    }


    /**
     * 验证码回调函数
     */
    private void code() {
        // 创建EventHandler对象
        eventHandler = new EventHandler() {
            public void afterEvent(int event, int result, Object data) {
                if (data instanceof Throwable) {
                    Throwable throwable = (Throwable) data;
                    final String msg = throwable.getMessage();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Gson gson = new Gson();

                            Code shopInfo = gson.fromJson(msg, Code.class);

                            Log.d(TAG, "run: " + shopInfo.getStatus() + msg);
                            if (shopInfo.getStatus() == 468) {
                                Toast.makeText(Res_pho_numActivity.this, "输入的验证码错误,请重新输入", Toast.LENGTH_SHORT).show();
                            }
                            if (shopInfo.getStatus() == 603) {
                                Toast.makeText(Res_pho_numActivity.this, "请填写正确的手机号码", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });

                } else {
                    if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {

                        // 处理你自己的逻辑
                        Log.d(TAG, "afterEvent: 获取成功");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(Res_pho_numActivity.this, "验证码获取成功,请注意查收", Toast.LENGTH_SHORT).show();
                            }
                        });
                    } else if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        //提价验证码
                        Log.d(TAG, "afterEvent: 验证成功");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //获取的手机号码
                                String str_mphone = forgetEdiPhone.getText().toString().trim();

                                //取出token
                                SharedPreferences sharedPreferences = getSharedPreferences("data", MODE_PRIVATE);  //使用sp取出用户的手机号码用作用户名
                                String token = sharedPreferences.getString("token", "token取出失败");
                                Log.d(TAG, "Res_pho_numActivity:  新手机号码:" + str_mphone + "新号码的token:" + token);
                                res_pho_numPersenter.ResetNum(token, str_mphone);
                            }
                        });
                    }
                }
            }
        };
    }


    /**
     * 等待弹出框
     */
    private void dialog() {
        pDialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
        pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
        pDialog.setTitleText("Loading");
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    public void loginSuccess(String msg) {
        new SweetAlertDialog(this, SweetAlertDialog.SUCCESS_TYPE)
                .setTitleText(msg)
                .setContentText("立即重新登录")
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        Intent intent = new Intent(Res_pho_numActivity.this, LoginActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);  //清空登录界面之前的所有Activity
                        startActivity(intent);
                    }
                }).show();
    }

    @Override
    public void loginFail(String msg) {
        pDialog.cancel();
        new SweetAlertDialog(this, SweetAlertDialog.ERROR_TYPE)
                .setTitleText(msg)
                .setContentText("请重新输入")
                .show();
    }

    @Override
    public void showToast(String msg) {

    }
}
